package com.tengju.bff.interfaces.manage.login;


import com.idanchuang.dc.open.data.sdk.base.internal.util.Md5Util;
import com.tengju.bff.interfaces.app.user.vo.ManageUserVO;
import com.tengju.bff.interfaces.login.facade.UserAccountFacade;
import com.tengju.bff.interfaces.manage.login.assembler.LoginAssembler;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.servlet.ManageEntrance;
import com.tengju.bff.interfaces.shared.servlet.NotTokenValid;
import com.tengju.bff.interfaces.shared.servlet.ServletContextUtil;
import com.tengju.bff.interfaces.shared.servlet.UserServletContext;
import com.tengju.user.application.archives.dto.UserLoginDTO;
import com.tengju.user.application.archives.dto.UserRegisterDTO;
import com.tengju.user.application.login.UserAccountService;
import com.tengju.user.application.login.dto.LoginDTO;
import com.tengju.user.application.login.dto.LogoutDTO;
import com.tengju.user.application.login.dto.RegisterDTO;
import com.tengju.user.application.login.vo.LoginVO;
import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.domain.model.login.UserType;
import com.tengju.user.domain.shared.DomainException;
import com.tengju.user.domain.shared.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@Api(tags = "后台用户登录接口")
@RequestMapping(value = "manage/login")
@Slf4j
@ManageEntrance
public class LoginController {

    @Autowired
    UserAccountService userAccountService;

    @Autowired
    UserAccountFacade userAccountFacade;

    @ApiOperation(value = "dt后台登录功能", notes = "dt后台登录功能")
    @RequestMapping(value = "usernameAndPwd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @NotTokenValid
    public ApiResponse<ManageUserVO> doLogin(@Valid @RequestBody UserLoginDTO userLoginDTO) {
        try {

            LoginDTO loginDTO = new LoginDTO(
                    userLoginDTO.getUsername(),
                    Md5Util.md5(userLoginDTO.getPwd()),
                    2,
                    2
            );
            LoginVO manageUser = userAccountFacade.login(loginDTO);
            if (manageUser == null) {
                return ApiResponse.newFailure(ResultCodeEnum.DT_LOGIN_ACCOUNT_ERROR);
            }
            return ApiResponse.newSuccess(LoginAssembler.manageUserToVO(manageUser));
        } catch (DomainException | ApplicationException e) {
            log.warn("username:{},登陆失败：", userLoginDTO.getUsername(), e);
            return ApiResponse.newFailure(ResultCodeEnum.BIZ_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("username:{},登陆异常：",userLoginDTO.getUsername(),  e);
            return ApiResponse.newFailure(ResultCodeEnum.SYS_EXCEPTION.getCode(), ResultCodeEnum.SYS_EXCEPTION.getMsg());
        }
    }

    @ApiOperation(value = "dt后台退出登录", notes = "dt后台退出登录")
    @RequestMapping(value = "doLogout", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @NotTokenValid
    public ApiResponse<Boolean> doLogout() {
        try {
            UserServletContext servletContext = ServletContextUtil.getServletContext();
            LogoutDTO logoutDTO = new LogoutDTO();
            logoutDTO.setUserId(servletContext.getStaffId().toString());
            logoutDTO.setUserType(2);
            userAccountFacade.logout(logoutDTO);
            return ApiResponse.newSuccess(true);
        } catch (DomainException | ApplicationException e) {
            log.warn("退出登陆失败：", e);
            return ApiResponse.newFailure(ResultCodeEnum.BIZ_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("退出登陆异常：", e);
            return ApiResponse.newFailure(ResultCodeEnum.SYS_EXCEPTION.getCode(), ResultCodeEnum.SYS_EXCEPTION.getMsg());
        }
    }

    @ApiOperation(value = "dt后台用户注册", notes = "dt后台用户注册")
    @RequestMapping(value = "addManageUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @NotTokenValid
    public ApiResponse<Boolean> addManageUser(@Valid @RequestBody UserRegisterDTO userRegisterDTO,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return ApiResponse.newFailure(ResultCodeEnum.PARAMETER_INVALID.getCode(),
                    bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        try {
            RegisterDTO registerDTO = new RegisterDTO(
                    userRegisterDTO.getUsername(),
                    userRegisterDTO.getPwd(),
                    UserType.STAFF.getVal(),
                    userRegisterDTO.getRealName());
            userAccountFacade.addManageUser(registerDTO);
            return ApiResponse.newSuccess(true);
        } catch (DomainException | ApplicationException e) {
            log.error("注册失败：", e);
            return ApiResponse.newFailure(ResultCodeEnum.BIZ_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("注册异常：", e);
            return ApiResponse.newFailure(ResultCodeEnum.SYS_EXCEPTION.getCode(),
                    ResultCodeEnum.SYS_EXCEPTION.getMsg());
        }
    }

}
